/**
 * =========================== 通用网络请求方法 ===========================
 */

//加入下面的代码

/**
 统一支付方法
type 1.微信支付 100.余额支付
payPassword 余额支付的时候才有这个值
*/
function pay(that, orderId, onSuccessCallBack, onFailCallBack) {
	uni.getProvider({
		service: 'payment',
		success: function(res) {
			console.log(res.provider)
			if (~res.provider.indexOf('wxpay')) {
				that.sendRequest({
					url: "api/order/user/getWeChatPrepareOrder",
					data: {
						orderId: orderId
					},
					page: that,
					success: function(res) {
						let data = res.data;
						// 仅作为示例，非真实参数信息。
						uni.showLoading({
							mask: true,
							title: "支付中"
						});
						// #ifdef MP-WEIXIN
						uni.requestPayment({
							provider: 'wxpay',
							appId: data.appid,
							timeStamp: data.timeStamp,
							nonceStr: data.nonce_str,
							package: data.packageStr,
							signType: data.sign_type,
							paySign: data.paySign,
							success: function(res) {
								uni.showLoading({
									mask: true,
									title: "查询支付结果"
								});
								console.log(res)
								//支付回调成功了开始查询支付状态是否成功

								// if (onSuccessCallBack != null) {
								// 	onSuccessCallBack("支付成功");
								// }
								isPaySuccess(that, orderId, "", 0,
									onSuccessCallBack,
									onFailCallBack)
							},
							fail: function(err) {
								console.log(err)
								uni.hideLoading()
								if (onFailCallBack != null) {
									onFailCallBack("支付失败");
								}
								// console.log('fail:' + JSON.stringify(err));
							}
						});
						// #endif
						// #ifdef APP-PLUS
						console.log(data.appid, data.mch_id, data.prepay_id, data.packageStr,
							data.nonce_str, data.timeStamp, data.paySign)
						uni.requestPayment({
							provider: 'wxpay',
							orderInfo: {
								appid: data.appid,
								partnerid: data.mch_id,
								prepayid: data.prepay_id,
								package: data.packageStr,
								noncestr: data.nonce_str,
								timestamp: data.timeStamp,
								sign: data.paySign
							},
							success: function(res) {
								uni.showLoading({
									mask: true,
									title: "查询支付结果"
								});
								console.log(res)
								//支付回调成功了开始查询支付状态是否成功

								// if (onSuccessCallBack != null) {
								// 	onSuccessCallBack("支付成功");
								// }
								isPaySuccess(that, orderId, "", 0,
									onSuccessCallBack, onFailCallBack)
							},
							fail: function(err) {
								console.log(err)
								uni.hideLoading()
								if (onFailCallBack != null) {
									onFailCallBack("支付失败");
								}
								// console.log('fail:' + JSON.stringify(err));
							}
						});
						// #endif

					},
					fail: function(e) {
						if (onFailCallBack != null) {
							onFailCallBack("支付失败");
						}
					},
					codeFail: function(res) {
						if (onFailCallBack != null) {
							onFailCallBack(res.message);
						}
					}
				})
			} else {
				if (onFailCallBack != null) {
					onFailCallBack("当前设备不支持支付");
				}
			}
		}
	});

}
/**
 qq里调用微信支付
*/
function payQQwx(that, orderId, onSuccessCallBack, onFailCallBack) {
	//首先提交微信的预订单
	that.sendRequest({
		url: "api/order/user/prepareByQQWx",
		data: {
			orderId: orderId
		},
		page: that,
		success: function(res) {
			let order = res.data
			console.log(order)
			qq.requestWxPayment({
				url: order.mwebUrl,
				referer: order.refererUrl,
				success(res) {
					console.log(res)
					uni.showLoading({
						mask: true,
						title: "查询支付结果"
					});
					console.log(res)
					//支付回调成功了开始查询支付状态是否成功

					// if (onSuccessCallBack != null) {
					// 	onSuccessCallBack("支付成功");
					// }
					isPaySuccess(that, orderId, "", 0, onSuccessCallBack,
						onFailCallBack)
				},
				fail(res) {
					console.log(res)
					uni.hideLoading()
					if (onFailCallBack != null) {
						onFailCallBack("支付失败");
					}
				}
			})
		},
		fail: function(e) {}
	})

}

async function dealIosUnDealOrder(that) {
	plus.payment.getChannels(
		function(channels) {
			console.log("channels-------------", channels);
			let find = false
			for (var i in channels) {
				if (channels[i].id == "appleiap") {
					find = true
					// console.log("channels[i]-----------", channels[i]);
					let iapChannel = channels[i];
					console.log("开始处理未完成的订单")
					iapChannel.restoreCompletedTransactions({
						manualFinishTransaction: true
					}, (transactionList) => {
						console.log("处理完完成的订单")
						console.log(transactionList)
						// let transactions = res


						//这里需要先请求服务器验证订单后再执行批量结束订单

						for (var i = 0; i < transactionList.length; i++) {

							let transaction = transactionList[i];

							// if (transaction.transactionState == 0) { //开始支付进程

							// } else if (transaction.transactionState == 1) { //支付成功但订单未关闭

							// } else if (transaction.transactionState == 2) { //错误的订单

							// } else if (transaction.transactionState == 3) { //存储的持续性消耗订单

							// } else if (transaction.transactionState == 4) { //处于队列中的事务，但其最终状态为等待外部操作实际未支付完成

							// }
							console.log("请求后台判断订单:" + transaction.payment.username)
							if (transaction.transactionState == 1 && transaction.payment
								.username != undefined &&
								transaction.payment.username !=
								null) { //请求订单式username就存的事订单id
								// console.log("请求后台判断订单:" + transaction.payment.username)
								that.sendRequest({
									url: "api/order/user/isPaySuccessNew",
									data: {
										orderId: transaction.payment.username,
										receipt: transaction.transactionReceipt
									},
									page: that,
									showLoading: 2,
									success: function(res) {
										let data = res.data;
										if (data == true) {
											// if (onSuccessCallBack != null) {
											// 	onSuccessCallBack("支付成功");
											// }
											iapChannel.finishTransaction(transaction,
												(res) => {
													console.log("结束存量成功但未处理订单")
													console.log(transaction)
												}, (err) => {});
										} else {
											//判断失败不处理
										}
									},
									fail: function(e) {},
									codeFail: function(res) {}

								})
							} else { //没有订单号的直接关闭
								iapChannel.finishTransaction(res[i], (res) => {
									console.log("结束存量异常订单")
								}, (err) => {});
							}
						}

					}, (err) => {})

				}
			}

			if (!find) {
				uni.hideLoading()
			}
		},
		function(e) {
			console.log("获取支付通道失败：" + e.message);
		}
	);
}

async function payIOS(that, orderId, productId, onSuccessCallBack, onFailCallBack) {
	let _this = this
	uni.showLoading({
		title: '检测支付环境...',
		mask: true
	})

	const IAPOrders = [productId];
	console.log("获得产品" + JSON.stringify(IAPOrders))
	//uni-app中将此function里的代码放入vue页面的onLoad生命周期中
	plus.payment.getChannels(
		function(channels) {
			console.log("channels-------------", channels);
			let find = false
			for (var i in channels) {
				if (channels[i].id == "appleiap") {
					find = true
					// console.log("channels[i]-----------", channels[i]);
					let iapChannel = channels[i];
					console.log("开始请求订单")
					uni.showLoading({
						title: '创建订单中...',
						mask: true
					})
					// iapChannel.restoreCompletedTransactions({
					// 	manualFinishTransaction: false
					// }, (res) => {
					// 	console.log("已处理完完成的订单")
					// }, (err) => {})

					iapChannel.requestOrder(
						IAPOrders,
						function(data) {
							// console.log(data, data.length);

							_this.applePay(iapChannel, that, productId, orderId, onSuccessCallBack,
								onFailCallBack)
						},
						function(errormsg) {
							console.log(
								"获取支付通道失败：" +
								JSON.stringify(errormsg) +
								"-" +
								errormsg.message
							);
							uni.showToast({
								title: "获取支付信息失败" + JSON.stringify(errormsg),
								icon: "none",
								duration: 2000
							});

						}
					);
				}
			}

			if (!find) {
				uni.hideLoading()
			}
		},
		function(e) {
			console.log("获取支付通道失败：" + e.message);
		}
	);
}


//苹果支付
function applePay(iapChannel, that, productId, orderId, onSuccessCallBack, onFailCallBack) {
	console.log("支付中", productId)
	uni.showLoading({
		title: '等待支付中',
		mask: true
	})
	uni.requestPayment({
		provider: 'appleiap',
		orderInfo: {
			productid: productId,
			manualFinishTransaction: true,
			username: orderId + "" //自定义透传参数里传入订单的id便于后面查询使用
		},
		success(transaction) {
			// uni.hideLoading()
			console.log("zhifu成功", transaction)
			uni.showToast({
				title: "验证结果",
				icon: "none",
				duration: 2000
			});

			console.log("验证结果")
			isPaySuccess(that, orderId, transaction.transactionReceipt, -5, function() {
					if (onSuccessCallBack != null) {
						onSuccessCallBack("支付成功");
					}
					//苹果支付回调成功
					iapChannel.finishTransaction(transaction, (res) => {
						console.log("结束订单")
					}, (err) => {});
				},
				onFailCallBack)
		},
		fail(e) {
			uni.hideLoading()
			uni.showToast({
				title: '支付失败或取消',
				icon: "none",
				duration: 2000
			});
		},
		complete() {
			// uni.hideLoading()
		}
	})
}


/**
 qq里调用微信支付
*/
function payWallet(that, orderId, onSuccessCallBack, onFailCallBack) {
	//首先提交微信的预订单
	that.sendRequest({
		url: "api/order/user/payByWallet",
		data: {
			orderId: orderId
		},
		page: that,
		success: function(res) {
			let order = res.data
			console.log(order)
			isPaySuccess(that, orderId, "", 0, onSuccessCallBack,
				onFailCallBack)
		},
		fail: function(e) {}
	})

}


function isPaySuccess(that, orderId, receipt, count, onSuccessCallBack, onFailCallBack) {
	uni.showLoading({
		mask: true,
		title: "查询支付结果,请勿退出"
	});
	console.log("第  " + count + "  次验证")
	// console.log(onSuccessCallBack)
	setTimeout(function() {
		uni.showLoading({
			mask: true,
			title: "查询支付结果,请勿退出"
		});
		//共计查询5秒钟
		that.sendRequest({
			url: "api/order/user/isPaySuccessNew",
			data: {
				orderId: orderId,
				receipt: receipt
			},
			page: that,
			showLoading: 2,
			success: function(res) {
				let data = res.data;
				if (data == true) {
					uni.hideLoading()
					if (onSuccessCallBack != null) {
						onSuccessCallBack("支付成功");
					}
				} else {
					count++;
					if (count >= 5) { //超过最大请求次数
						if (onFailCallBack != null) {
							uni.hideLoading()
							onFailCallBack("查询支付结果失败，请稍后再试");
						}
					} else { //继续循环请求
						setTimeout(function() {
							isPaySuccess(that, orderId, receipt, count, onSuccessCallBack,
								onFailCallBack);
						}, 1000 * Math.abs(count))
					}
				}
			},
			fail: function(e) {
				uni.hideLoading()
				if (onFailCallBack != null) {
					onFailCallBack("支付失败");
				}
			},
			codeFail: function(res) {
				uni.hideLoading()
				console.log(res)
				if (onFailCallBack != null) {
					onFailCallBack(res.msg);
				}
			}

		})
	}, 1000)

}

/**
打赏订单
payOrigin 1.小程序支付 2.app支付
*/
function payAli(that, orderId, userId, onSuccessCallBack, onFailCallBack) {
	uni.getProvider({
		service: 'payment',
		success: function(res) {
			if (~res.provider.indexOf('alipay')) {
				that.sendRequest({
					url: "api/order/user/getAliPayPrepareOrder",
					data: {
						orderId: orderId,
						userId: userId
					},
					page: that,
					success: function(res) {
						let orderInfo = res.data;
						console.log(orderInfo)

						// 仅作为示例，非真实参数信息。
						uni.showLoading({
							mask: true,
							title: "支付中"
						});

						uni.requestPayment({
							provider: 'alipay',
							orderInfo: orderInfo, //微信、支付宝订单数据 【注意微信的订单信息，键值应该全部是小写，不能采用驼峰命名】
							success: function(res) {
								uni.showLoading({
									mask: true,
									title: "查询支付结果"
								});
								console.log(res)
								//支付回调成功了开始查询支付状态是否成功

								// if (onSuccessCallBack != null) {
								// 	onSuccessCallBack("支付成功");
								// }
								isPaySuccess(that, orderId, "", 0,
									onSuccessCallBack,
									onFailCallBack)
							},
							fail: function(err) {
								uni.hideLoading()
								console.log('fail:' + JSON.stringify(err));
								uni.showModal({
									content: err.errMsg,
									showCancel: false
								})
							}
						});



						// uni.requestPayment({
						// 	provider: 'alipay',
						// 	orderInfo: {
						// 		appid: data.appid,
						// 		partnerid: data.mch_id,
						// 		prepayid: data.prepay_id,
						// 		package: data.packageStr,
						// 		noncestr: data.nonce_str,
						// 		timestamp: data.timeStamp,
						// 		sign: data.paySign
						// 	},
						// 	success: function(res) {
						// 		uni.showLoading({
						// 			mask: true,
						// 			title: "查询支付结果"
						// 		});
						// 		console.log(res)
						// 		//支付回调成功了开始查询支付状态是否成功

						// 		// if (onSuccessCallBack != null) {
						// 		// 	onSuccessCallBack("支付成功");
						// 		// }
						// 		isPaySuccess2(that, orderId,"", 0, onSuccessCallBack,
						// 			onFailCallBack)
						// 	},
						// 	fail: function(err) {
						// 		console.log(err)
						// 		uni.hideLoading()
						// 		if (onFailCallBack != null) {
						// 			onFailCallBack("支付失败");
						// 		}
						// 		// console.log('fail:' + JSON.stringify(err));
						// 	}
						// });


					},
					fail: function(e) {
						if (onFailCallBack != null) {
							onFailCallBack("支付失败");
						}
					},
					codeFail: function(res) {
						if (onFailCallBack != null) {
							onFailCallBack(res.msg);
						}
					}
				})
			} else {
				if (onFailCallBack != null) {
					onFailCallBack("该支付方式调用失败");
				}
			}
		}
	});
}

module.exports = {
	pay: pay,
	payAli: payAli,
	payQQwx: payQQwx,
	payIOS: payIOS,
	payWallet: payWallet,
	applePay: applePay,
	dealIosUnDealOrder: dealIosUnDealOrder
}